package cn.itsource.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求中拿到U-Token请求头及对应的值
        String token = request.getHeader("U-TOKEN");
        //判断token不是null
        if(token != null){
            //通过获取的token去redis中查询
            Object loginInfo = redisTemplate.opsForValue().get(token);
            if(loginInfo != null){
                //查到,放行，刷新有效时间30分钟
                redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(" {\"success\":false,\"resultObj\":\"nologin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
